<?php

namespace addons\tools\controller\api\v1;


use addons\third\library\Service;
use addons\third\model\Third;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use think\Config;
use think\Session;
use think\Validate;

class Login extends Api
{
    protected $noNeedLogin = ['*'];

    /**
     * 会员登录
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account', '');
        $password = $this->request->post('password', '');

        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }

        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $this->success(__('Logged in successful'), [
                'token'   => $this->auth->getToken(),
                'user_id' => $this->auth->id
            ]);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 重置密码
     *
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $type = $this->request->param("type");
        $mobile = $this->request->param("mobile");
        $email = $this->request->param("email");
        $newpassword = $this->request->param("newpassword");
        $captcha = $this->request->param("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }

        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $code = $this->request->post('code');
        $invite_code = $this->request->post('invite_code');
        if (!$mobile || !$captcha || !$code) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
//        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
//            $this->error(__('Captcha is incorrect'));
//        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, ['invite_code' => $invite_code]);
            if ($ret) {
                $params = [
                    'appid'      => Config::get('play.wxappid'),
                    'secret'     => Config::get('play.wxappsecret'),
                    'js_code'    => $code,
                    'grant_type' => 'authorization_code'
                ];
                $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
                $json = (array)json_decode($result['msg'], true);
                if (isset($json['session_key']) && $json['session_key']) {
                    $thirdInfo = Third::where('openid', $json['openid'])->find();
                    if (!$thirdInfo)
                        Third::create([
                            'user_id'  => $this->auth->id,
                            'platform' => 'wechat',
                            'apptype'  => 'miniapp',
                            'openid'   => $json['openid'],
                        ]);
                }

            }
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['token' => $this->auth->getToken(), 'user_info' => $this->auth->getUser()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function register()
    {
        $username = $this->request->param('username');
        $password = $this->request->param('password');
        $mobile = $this->request->param('mobile');
        $code = $this->request->param('code');
        $invite_code = $this->request->post('invite_code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
//        $ret = Sms::check($mobile, $code, 'register');
//        if (!$ret) {
//            $this->error(__('Captcha is incorrect'));
//        }

        $ret = $this->auth->register($username, $password, '', $mobile, []);
        if ($ret) {
            $this->success(__('Sign up successful'), [
                'token'   => $this->auth->getToken(),
                'user_id' => $this->auth->id
            ]);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * Undocumented function
     * 第三方登录[绑定] 小程序
     * @return void
     */
    public function wxLogin()
    {
        $code = $this->request->post("code");
        $invite_code = $this->request->post('invite_code');
        if (!$code) {
            $this->error("参数不正确");
        }
        $third = get_addon_info('third');
        if (!$third || !$third['state']) {
            $this->error("请在后台插件管理安装并配置第三方登录插件");
        }
        $config = get_addon_config('third');
        $params = [
            'appid'      => $config['mini']['app_id'],
            'secret'     => $config['mini']['app_secret'],
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        ];

        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
        if ($result['ret']) {
            $json = (array)json_decode($result['msg'], true);
            if (isset($json['openid'])) {
                $userinfo = [
                    'platform'      => 'wechat',
                    'apptype'       => 'miniapp',
                    'openid'        => $json['openid'],
                    'userinfo'      => [
                        'nickname' => '',
                        'avatar'   => ''
                    ],
                    'access_token'  => $json['session_key'],
                    'refresh_token' => '',
                    'expires_in'    => isset($json['expires_in']) ? $json['expires_in'] : 0,
                    'unionid'       => isset($json['unionid']) ? $json['unionid'] : ''
                ];
                Service::connect($userinfo['platform'], $userinfo, ['invite_code' => $invite_code]);
                $this->success('授权成功!', ['token' => $this->auth->getToken()]);
            }
            $this->error('授权失败');
        }
        $this->error("授权失败");
    }

    /**
     * app登录
     * @return void
     */
    public function appLogin()
    {
        $code = $this->request->post("code");
        $scope = $this->request->post("scope");
        $invite_code = $this->request->post('invite_code');
        if (!$code) {
            $this->error("参数不正确");
        }
        $third = get_addon_info('third');
        if (!$third || !$third['state']) {
            $this->error("请在后台插件管理安装并配置第三方登录插件");
        }
        Session::set('state', $code);
        $config = [
            'app_id'     => Config::get('cms.app_id'),
            'app_secret' => Config::get('cms.app_secret'),
            'scope'      => $scope
        ];
        $wechat = new \addons\third\library\Wechat($config);
        $userinfo = $wechat->getUserInfo(['code' => $code, 'state' => $code]);
        if (!$userinfo) {
            $this->error(__('操作失败'));
        }
        //判断是否需要绑定
        $userinfo['apptype'] = 'native';
        $userinfo['platform'] = 'wechat';

        $third = [
            'avatar'   => $userinfo['userinfo']['avatar'],
            'nickname' => $userinfo['userinfo']['nickname']
        ];
        $user = null;
        if (Service::isBindThird($userinfo['platform'], $userinfo['openid'], $userinfo['apptype'], $userinfo['unionid'])) {
            Service::connect($userinfo['platform'], $userinfo, ['invite_code' => $invite_code]);
            $user = $this->auth->getUserinfo();
        } else {
            Session::set('third-userinfo', $userinfo);
        }
        $this->success('授权成功!', ['user' => $user, 'third' => $third]);
    }

    /**
     * qq
     * @author: wooooh
     * @dateTime: 2022/5/13 11:48
     */
    public function qqLogin()
    {
        $code = $this->request->post('code');
        if (!$code) $this->error('参数错误');
        $invite_code = $this->request->post('invite_code');
        $third = get_addon_info('third');
        if (!$third || !$third['state']) {
            $this->error("请在后台插件管理安装并配置第三方登录插件");
        }
        $config = get_addon_config('third');
        $param = [
            'appid'      => $config['qq']['app_id'],
            'secret'     => $config['qq']['app_secret'],
            'js_code'    => $code,
            'grant_type' => 'authorization_code',
        ];
        $ret = Http::get('https://api.q.qq.com/sns/jscode2session', $param);
        $json = json_decode($ret, true);
        if ($json['errcode'] == 0 && $json['errmsg'] == '') {
            if (isset($json['openid'])) {
                $userinfo = [
                    'platform'      => 'qq',
                    'apptype'       => 'qqminiapp',
                    'openid'        => $json['openid'],
                    'userinfo'      => [
                        'nickname' => '',
                        'avatar'   => ''
                    ],
                    'access_token'  => $json['session_key'],
                    'refresh_token' => '',
                    'expires_in'    => isset($json['expires_in']) ? $json['expires_in'] : 0,
                    'unionid'       => isset($json['unionid']) ? $json['unionid'] : ''
                ];
                Service::connect($userinfo['platform'], $userinfo, ['invite_code' => $invite_code]);
                $this->success('授权成功!', ['token' => $this->auth->getToken()]);
            }
        }
        $this->error('授权失败');
    }

    /**
     * 抖音登录
     * @author: wooooh
     * @dateTime: 2022/5/13 17:17
     */
    public function tiktokLogin()
    {
        $code = $this->request->post('code', '');
        if (!$code) $this->error('参数错误');
        $anonymous_code = $this->request->post('anonymous_code', '');
        $third = get_addon_info('third');
        if (!$third || !$third['state']) {
            $this->error("请在后台插件管理安装并配置第三方登录插件");
        }
        $invite_code = $this->request->post('invite_code');
        $config = get_addon_config('third');
        $param = [
            'appid'          => $config['tiktok']['app_id'],
            'secret'         => $config['tiktok']['app_secret'],
            'anonymous_code' => $anonymous_code,
            'code'           => $code,
        ];
        $ret = Http::post('https://developer.toutiao.com/api/apps/v2/jscode2session', json_encode($param), [], ['content-type' => "application/json"]);
        $json = json_decode($ret, true);
        if ($json['err_no'] == 0 && $json['err_tips'] == 'success') {
            if (isset($json['data']['openid'])) {
                $userinfo = [
                    'platform'      => 'tiktok',
                    'apptype'       => 'tiktok',
                    'openid'        => $json['data']['openid'],
                    'userinfo'      => [
                        'nickname' => '',
                        'avatar'   => ''
                    ],
                    'access_token'  => $json['data']['session_key'],
                    'refresh_token' => '',
                    'expires_in'    => isset($json['data']['expires_in']) ? $json['data']['expires_in'] : 0,
                    'unionid'       => isset($json['data']['unionid']) ? $json['data']['unionid'] : ''
                ];
                Service::connect($userinfo['platform'], $userinfo, ['invite_code' => $invite_code]);
                $this->success('授权成功!', ['token' => $this->auth->getToken()]);
            }
        } else {
            $this->error($json['err_no'] . '-' . $json['err_tips']);
        }
        $this->error('授权失败');
    }
}